<?php

class Rcp_Auth implements Zend_Auth_Adapter_Interface {
	
	/**
	 * 
	 * @var Rcp_AuthData_ILoginData
	 */
	protected $_loginData = null;

	/**
	 * 
	 * @var string
	 */
	protected $_namespace = null;
	
	/**
	 *
	 * @var RcpUsers
	 */
	private $user = null;
	
	/**
	 *
	 * @var Rcp_Auth
	 */
	static private $_instance = null;
	
	public static function getInstance() {
		if (self::$_instance === null) {
			self::$_instance = new self();
			self::$_instance->init();
		}
		return self::$_instance;
	}

	public function authenticate() {
		$this->_session->auth = false;		
		$this->user = $this->_loginData->getUser();
		if (!$this->user instanceof RcpUsers) {
			return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, $this->_loginData->getId(), array('Invalid login'));
		}
		$this->_session->auth = true;
		$this->_session->userId = $this->user->getId();
		return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $this->_loginData->getId());
	}
	
	public static function init() {
		self::$_instance->_namespace = Rcp_Core::getInstance()->getConfigs()->session->namespace;
		self::$_instance->_session = new Zend_Session_Namespace(self::$_instance->_namespace);
		if (self::$_instance->_session->auth === null || self::$_instance->_session->userId === null) {
			self::$_instance->_session->auth = false;
			self::$_instance->_session->userId = null;
		} else {
			self::$_instance->user = RcpUsersQuery::create()->findOneByIdWithBaseData(self::$_instance->_session->userId);
			if (!self::$_instance->user instanceof RcpUsers) {
				self::$_instance->_session->auth = false;
				self::$_instance->_session->userId = null;
			}
		}
	}
	
	public function logout() {
		$this->_session->auth = false;
		$this->_session->userId = null;
		$this->user = null;
	}
	
	public function setLoginData($loginData) {
		$this->_loginData = $loginData;
		return $this;
	}

	public function getUser() {
		return $this->user;
	}
	
	public function isAuth() {
		return $this->_session->auth;
	}

}